# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(optparse)
library(magrittr)
library(ggpubr)
library(tidyverse)
library(jsonlite)
library(car)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configJson <- fromJSON(opt$config)
diffMethod <- configJson$method
pValue <- configJson$pValue %>%
  as.numeric()
fdr <- configJson$fdr %>%
  as.numeric()

my.test <- function(data, method) {
  p <- 0
  curMethod <- method
  if (curMethod == "auto") {
    sTest <- data %>%
      group_by(ClassNote) %>%
      summarise(p = {
        var <- var(value)
        if (var == 0) {
          0
        }else shapiro.test(value)$p.value
      },.groups = "keep")
    bTest <- leveneTest(value ~ ClassNote, data)
    bp <- bTest$`Pr(>F)`[1]
    if (all(sTest$p > 0.05) && bp > 0.05) {
      curMethod <- "anova"
    }else {
      curMethod <- "kw"
    }
  }

  if (curMethod == "kw") {
    test <- kruskal.test(value ~ ClassNote, data = data)
    p <- test$p.value
    if (is.na(p)) {
      p <- 1
    }
    curMethod <- "kruskal.test"
  }else if (curMethod == "anova") {
    test <- compare_means(value ~ ClassNote, data = data, method = "anova")
    p <- test$p
    curMethod <- "anova"
  }
  list(p = p, method = curMethod)
}

options(digits = 3)

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleIds <- sampleInfo$SampleID

groups <- unique(sampleInfo$ClassNote)

allData <- read_tsv(opt$i) %>%
  rename(Metabolite = 1) %>%
  select(c("Metabolite", sampleIds)) %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    kwData <- result %>%
      select(-c("Metabolite")) %>%
      gather("SampleID", "value") %>%
      inner_join(sampleInfo, by = c("SampleID"))
    for (group in groups) {
      sampleIds <- sampleInfo %>%
        filter(ClassNote == group) %>%
        .$SampleID
      groupData <- result[sampleIds] %>%
        unlist()
      result[, paste0(group, ".Mean")] <- mean(groupData)
      result[, paste0(group, ".Median")] <- median(groupData)
      result[, paste0(group, ".SD")] <- sd(groupData)
      iqr11 <- quantile(groupData, 0.25)
      iqr12 <- quantile(groupData, 0.75)
      iqr1 <- paste0("[", iqr11, ",", iqr12, "]")
      result[, paste0(group, ".IQR")] <- iqr1
    }
    rs <- my.test(kwData, diffMethod)
    result$P <- rs$p
    result$test.method <- rs$method
    result
  }) %>%
  select(-c(sampleInfo$SampleID)) %>%
  as.data.frame()

data <- allData %>%
  mutate(FDR = p.adjust(P, method = "fdr")) %>%
  select(-"test.method", everything(), "test.method")

print(head(data))

parent <- paste0("./")
allFileName <- paste0(parent, "/AllMet_Test.csv")
write.csv(data, allFileName, row.names = FALSE)

finalDf <- read_csv("AllMet_Test.csv") %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    p <- result[1, "P"]
    q <- result[1, "FDR"]
    value <- if (p < pValue & q < fdr) {
      1
    }else 0
    result$IS_Uni_P_Sig <- value
    result
  }) %>%
  filter(IS_Uni_P_Sig == 1) %>%
  select(-c("IS_Uni_P_Sig"))

outFileName <- paste0(parent, "/Diff_Met_Test.csv")
write_csv(finalDf, outFileName)

diffData <- finalDf %>%
  select(c("Metabolite"))

write_csv(diffData, "Diff_Metabolite.csv")












